import { defineStore } from 'pinia';
import type {
  baseWorkshop,
  WorkshopQueryParams,
  WorkshopPageResult,
  WorkshopCreateParams,
  WorkshopUpdateParams,
  WorkshopStatusParams
} from '@/types/base/BaseWorkshop';

// 模拟车间数据
const mockWorkshops: baseWorkshop[] = [
  {
    workshop_id: 1,
    workshop_code: 'WS-001',
    workshop_name: '一号生产车间',
    warehouse_id: 1,
    warehouse_name: '成品仓库',
    workshop_type: 1,
    production_capacity: 1000,
    manager_name: '张三',
    phone_number: '13800138001',
    address: '厂区A栋1楼',
    description: '主要生产基础零部件',
    is_active: true,
    is_deleted: false,
    created_by: 'admin',
    created_at: '2024-01-15 10:30:00',
    updated_by: 'admin',
    updated_at: '2024-01-15 10:30:00'
  },
  {
    workshop_id: 2,
    workshop_code: 'WS-002',
    workshop_name: '装配车间',
    warehouse_id: 1,
    warehouse_name: '成品仓库',
    workshop_type: 2,
    production_capacity: 500,
    manager_name: '李四',
    phone_number: '13800138002',
    address: '厂区A栋2楼',
    description: '负责产品组装',
    is_active: true,
    is_deleted: false,
    created_by: 'admin',
    created_at: '2024-01-15 10:31:00',
    updated_by: 'admin',
    updated_at: '2024-01-15 10:31:00'
  },
  {
    workshop_id: 3,
    workshop_code: 'WS-003',
    workshop_name: '包装车间',
    warehouse_id: 1,
    warehouse_name: '成品仓库',
    workshop_type: 3,
    production_capacity: 800,
    manager_name: '王五',
    phone_number: '13800138003',
    address: '厂区B栋1楼',
    description: '产品包装与质检',
    is_active: false,
    is_deleted: false,
    created_by: 'admin',
    created_at: '2024-01-15 10:32:00',
    updated_by: 'admin',
    updated_at: '2024-01-15 10:32:00'
  }
];

export const useBaseWorkShopStore = defineStore('baseWorkShop', {
  state: () => ({
    workshops: [] as baseWorkshop[],
    currentWorkshop: null as baseWorkshop | null,
    loading: false,
    currentPage: 1,
    pageSize: 10,
    total: 0,
    queryParams: {} as WorkshopQueryParams
  }),

  getters: {
    // 获取当前页的车间列表
    currentPageWorkshops: (state) => {
      // 如果有查询参数，进行过滤
      if (Object.keys(state.queryParams).length > 0) {
        return state.workshops.filter((workshop: baseWorkshop) => {
          // 车间编码筛选
          if (state.queryParams.workshop_code && !workshop.workshop_code.includes(state.queryParams.workshop_code)) {
            return false;
          }
          // 车间名称筛选
          if (state.queryParams.workshop_name && !workshop.workshop_name.includes(state.queryParams.workshop_name)) {
            return false;
          }
          // 车间类型筛选
          if (state.queryParams.workshop_type !== undefined && workshop.workshop_type !== state.queryParams.workshop_type) {
            return false;
          }
          // 状态筛选
          if (state.queryParams.is_active !== undefined && workshop.is_active !== state.queryParams.is_active) {
            return false;
          }
          // 仓库ID筛选
          if (state.queryParams.warehouse_id !== undefined && workshop.warehouse_id !== state.queryParams.warehouse_id) {
            return false;
          }
          return true;
        });
      }
      return state.workshops;
    },

    // 获取分页后的车间列表
    paginatedWorkshops: (state) => {
      const filtered = state.queryParams ? state.workshops.filter((workshop: baseWorkshop) => {
        // 车间编码筛选
        if (state.queryParams.workshop_code && !workshop.workshop_code.includes(state.queryParams.workshop_code)) {
          return false;
        }
        // 车间名称筛选
        if (state.queryParams.workshop_name && !workshop.workshop_name.includes(state.queryParams.workshop_name)) {
          return false;
        }
        // 车间类型筛选
        if (state.queryParams.workshop_type !== undefined && workshop.workshop_type !== state.queryParams.workshop_type) {
          return false;
        }
        // 状态筛选
        if (state.queryParams.is_active !== undefined && workshop.is_active !== state.queryParams.is_active) {
          return false;
        }
        // 仓库ID筛选
        if (state.queryParams.warehouse_id !== undefined && workshop.warehouse_id !== state.queryParams.warehouse_id) {
          return false;
        }
        return true;
      }) : state.workshops;

      const startIndex = (state.currentPage - 1) * state.pageSize;
      const endIndex = startIndex + state.pageSize;
      return filtered.slice(startIndex, endIndex);
    }
  },

  actions: {
    // 获取车间列表
    async getWorkshops(params: WorkshopQueryParams = {}) {
      this.loading = true;
      try {
        // 在实际项目中，这里应该是API调用
        // const response = await api.get('/api/workshops', { params });
        // this.workshops = response.data.list;
        // this.total = response.data.total;

        // 使用模拟数据
        this.queryParams = params;
        this.workshops = [...mockWorkshops];
        this.total = this.currentPageWorkshops.length;
        this.currentPage = params.page_number || 1;
        this.pageSize = params.page_size || 10;

        return {
          list: this.paginatedWorkshops,
          total: this.total,
          page_size: this.pageSize,
          page_number: this.currentPage
        } as WorkshopPageResult;
      } catch (error) {
        console.error('获取车间列表失败:', error);
        // 出错时也返回模拟数据
        this.workshops = [...mockWorkshops];
        this.total = this.workshops.length;
        return {
          list: this.paginatedWorkshops,
          total: this.total,
          page_size: this.pageSize,
          page_number: this.currentPage
        } as WorkshopPageResult;
      } finally {
        this.loading = false;
      }
    },

    // 获取车间详情
    async getWorkshopDetail(workshopId: number) {
      this.loading = true;
      try {
        // 在实际项目中，这里应该是API调用
        // const response = await api.get(`/api/workshops/${workshopId}`);
        // this.currentWorkshop = response.data;

        // 使用模拟数据
        const workshop = this.workshops.find(w => w.workshop_id === workshopId) || mockWorkshops.find(w => w.workshop_id === workshopId);
        this.currentWorkshop = workshop || null;
        return this.currentWorkshop;
      } catch (error) {
        console.error('获取车间详情失败:', error);
        // 出错时尝试从模拟数据中获取
        const workshop = mockWorkshops.find(w => w.workshop_id === workshopId);
        this.currentWorkshop = workshop || null;
        return this.currentWorkshop;
      } finally {
        this.loading = false;
      }
    },

    // 创建车间
    async createWorkshop(params: WorkshopCreateParams) {
      this.loading = true;
      try {
        // 在实际项目中，这里应该是API调用
        // const response = await api.post('/api/workshops', params);
        // const newWorkshop = response.data;
        // this.workshops.unshift(newWorkshop);
        // return newWorkshop;

        // 使用模拟数据
        const newWorkshop: baseWorkshop = {
          workshop_id: Date.now(),
          workshop_code: params.workshop_code,
          workshop_name: params.workshop_name,
          warehouse_id: params.warehouse_id,
          warehouse_name: '成品仓库', // 模拟数据，实际应从仓库管理获取
          workshop_type: params.workshop_type,
          production_capacity: params.production_capacity,
          manager_name: params.manager_name,
          phone_number: params.phone_number,
          address: params.address,
          description: params.description || '',
          is_active: true,
          is_deleted: false,
          created_by: 'admin',
          created_at: new Date().toISOString(),
          updated_by: 'admin',
          updated_at: new Date().toISOString()
        };
        this.workshops.unshift(newWorkshop);
        return newWorkshop;
      } catch (error) {
        console.error('创建车间失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 更新车间
    async updateWorkshop(params: WorkshopUpdateParams) {
      this.loading = true;
      try {
        // 在实际项目中，这里应该是API调用
        // const response = await api.put(`/api/workshops/${params.workshop_id}`, params);
        // const updatedWorkshop = response.data;
        // const index = this.workshops.findIndex(w => w.workshop_id === params.workshop_id);
        // if (index !== -1) {
        //   this.workshops[index] = updatedWorkshop;
        // }
        // return updatedWorkshop;

        // 使用模拟数据
        const index = this.workshops.findIndex(w => w.workshop_id === params.workshop_id);
        if (index !== -1) {
          const updatedWorkshop: baseWorkshop = {
            ...this.workshops[index],
            ...params,
            updated_by: 'admin',
            updated_at: new Date().toISOString()
          };
          this.workshops[index] = updatedWorkshop;
          if (this.currentWorkshop && this.currentWorkshop.workshop_id === params.workshop_id) {
            this.currentWorkshop = updatedWorkshop;
          }
          return updatedWorkshop;
        }
        throw new Error('车间不存在');
      } catch (error) {
        console.error('更新车间失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 删除车间
    async deleteWorkshop(workshopId: number) {
      this.loading = true;
      try {
        // 在实际项目中，这里应该是API调用
        // await api.delete(`/api/workshops/${workshopId}`);
        // this.workshops = this.workshops.filter(w => w.workshop_id !== workshopId);
        // if (this.currentWorkshop && this.currentWorkshop.workshop_id === workshopId) {
        //   this.currentWorkshop = null;
        // }

        // 使用模拟数据
        this.workshops = this.workshops.filter(w => w.workshop_id !== workshopId);
        if (this.currentWorkshop && this.currentWorkshop.workshop_id === workshopId) {
          this.currentWorkshop = null;
        }
      } catch (error) {
        console.error('删除车间失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 切换车间状态
    async toggleWorkshopStatus(params: WorkshopStatusParams) {
      this.loading = true;
      try {
        // 在实际项目中，这里应该是API调用
        // const response = await api.patch(`/api/workshops/${params.workshop_id}/status`, { is_active: params.is_active });
        // const updatedWorkshop = response.data;
        // const index = this.workshops.findIndex(w => w.workshop_id === params.workshop_id);
        // if (index !== -1) {
        //   this.workshops[index] = updatedWorkshop;
        // }
        // return updatedWorkshop;

        // 使用模拟数据
        const index = this.workshops.findIndex(w => w.workshop_id === params.workshop_id);
        if (index !== -1) {
          const updatedWorkshop: baseWorkshop = {
            ...this.workshops[index],
            is_active: params.is_active,
            updated_by: 'admin',
            updated_at: new Date().toISOString()
          };
          this.workshops[index] = updatedWorkshop;
          if (this.currentWorkshop && this.currentWorkshop.workshop_id === params.workshop_id) {
            this.currentWorkshop = updatedWorkshop;
          }
          return updatedWorkshop;
        }
        throw new Error('车间不存在');
      } catch (error) {
        console.error('切换车间状态失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 设置查询参数
    setQueryParams(params: WorkshopQueryParams) {
      this.queryParams = params;
      this.currentPage = 1;
    },

    // 重置查询参数
    resetQueryParams() {
      this.queryParams = {};
      this.currentPage = 1;
      this.pageSize = 10;
    },

    // 设置分页
    setPagination(page: number, pageSize: number) {
      this.currentPage = page;
      this.pageSize = pageSize;
    },

    // 清空当前车间
    clearCurrentWorkshop() {
      this.currentWorkshop = null;
    }
  }
});
